package com.huynhchihieu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huynhchihieu.dao.RoleDAO;
import com.huynhchihieu.dao.UserDAO;
import com.huynhchihieu.dao.UserRoleDao;
import com.huynhchihieu.domain.Domainuser;
import com.huynhchihieu.domain.RegistrationForm;
import com.huynhchihieu.exception.DuplicateEmailException;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserDAO userDAO;
    
    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    RoleDAO roleDAO;
    
    @Autowired
	private BCryptPasswordEncoder passwordEncoder;
 
    public Domainuser getUserByEmail(String email) {
        return userDAO.getUserByEmail(email);
    }


	public void createUser(Domainuser user, int roleId) {
		// insert user
		String encodedPassword = passwordEncoder.encode(user.getPassword());
		user.setPassword(encodedPassword);
		user = userDAO.createUser(user);
		 
		 // insert user_role
		 userRoleDao.createUserRole(user.getUserId(), roleId);
		 
	}
	
	public Domainuser registerNewUserAccount(RegistrationForm userAccountData) throws DuplicateEmailException{
		// check duplicate email
		if (emailExist(userAccountData.getEmail())) {
            throw new DuplicateEmailException("The email address: " + userAccountData.getEmail() + " is already in use.");
        }
		
		String encodedPassword = passwordEncoder.encode(userAccountData.getPassword());
		 
        Domainuser.Builder userBuilder = Domainuser.getBuilder()
                .email(userAccountData.getEmail())
                .firstName(userAccountData.getFirstName())
                .lastName(userAccountData.getLastName())
                .password(encodedPassword);
 
        if (userAccountData.isSocialSignIn()) {
        	userBuilder.signInProvider(userAccountData.getSignInProvider());
        }
 
        Domainuser registered = userBuilder.build();
		
		
		
        /*Domainuser user = new Domainuser();
		user.setLogin(userAccountData.getEmail());
		// encode
		user.setPassword(passwordEncoder.encode(userAccountData.getPassword())); */
        
        
		// insert user
        registered= userDAO.createUser(registered);
		// insert user_role
		userRoleDao.createUserRole(registered.getUserId(), userAccountData.getRoleId());
		return registered;
	}


	private boolean emailExist(String email) {
		// using login instead of email
		 Domainuser user = userDAO.getUserByEmail(email);
		 
	        if (user != null) {
	            return true;
	        }
	 
	        return false;
	}
 
}
